<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div class="table_content ">
      <!-- ====== 表格上方的筛选条件 start ======-->
      <div class="table_filter flb">
        <div class="crumbs flex_start">
          <span class="crumbs_active">公司列表</span>
        </div>
        <div class="flr">
          <div v-if="roleType != 1" class="mr10">
            <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="showDilogBtn('addDialogVisible')">
              <img src="@/assets/img/orderManagement/add.png" alt="添加公司" />
              <span class="ml5">添加公司</span>
            </el-button>
          </div>
          <el-button type="text" class="public_confirm_btn pub_button" @click="getDataList"> 搜索 </el-button>
        </div>
      </div>
      <!-- ====== 表格上方的筛选条件 end ======-->
      <el-table ref="multipleTable" size="mini" :data="tableData" tooltip-effect="dark" border :height="`${536 * $f}px`" class="wp100 mt12" :span-method="arraySpanMethod" @selection-change="handleSelectionChange">
        <el-table-column label="公司名称" show-overflow-tooltip prop="companyName" align="center" :min-width="`${250 * $f}`" />
        <el-table-column label="编码" show-overflow-tooltip prop="companyCode" align="center" :min-width="`${36 * $f}`" />
        <el-table-column label="税号" show-overflow-tooltip prop="taxNo" align="center" :min-width="`${100 * $f}`" />
        <el-table-column label="开户行" show-overflow-tooltip prop="bank" align="center" :min-width="`${200 * $f}`" />
        <el-table-column label="银行卡号" show-overflow-tooltip prop="address" align="center" :min-width="`${200 * $f}`" />
        <el-table-column label="审核状态" show-overflow-tooltip align="center" :width="`${100 * $f}`">
          <template slot-scope="{ row }">
            <span v-if="auditList[Number(row.auditStatus) - 1]" :class="[row.auditStatus === '3' ? 'cGR' : row.auditStatus === '4' ? 'cRD2' : 'cYE']">{{ auditList[Number(row.auditStatus) - 1] }}</span>
            <span v-else>未申请</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" :width="`${220 * $f}`">
          <template slot-scope="{ row }">
            <el-button v-if="row.auditStatus == '1' || row.auditStatus == null" class="pub_button public_1EB398_btn" type="text" size="mini" @click="completeCompany(row)">完善公司信息</el-button>
            <el-button v-if="row.auditStatus == '4'" class="pub_button public_1EB398_btn" type="text" size="mini" @click="lookReruseBtn(row)">查看驳回原因</el-button>
            <el-button class="pub_button public_1EB398_btn" type="text" size="mini" @click="goPage('layout/employeeInfo', row)">员工信息</el-button>
            <el-button type="text" class="pub_button public_1EB398_btn" size="mini" @click="editBtnClick(row)">编辑</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <PageEmptyData />
        </template>
      </el-table>
      <div ref="pubPageinationRef" class="pub_pageination flex_center mt18">
        <el-pagination background layout="total,prev, pager, next" :total="tableData.length" :page-size="tableData.length"> </el-pagination>
      </div>
    </div>
    <!-- 删除提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmDelete" />
    <!-- 信息反馈弹窗 -->
    <PageDialog :title="'驳回原因'" :dialog-visible="informationFeedbackVisilble" :width="`${$f * 500}px`" :submit-text="'重新提交'" @close="closeDialog" @submit="reloadUploadBtn">
      <div class="flex_center_column">
        <img src="@/assets/img/information/informationFeedback.png" class="informationFeedback_img" />
        <div class="informationFeedback_title mt10">
          资质审核未通过
        </div>
        <p class="informationFeedback_tips mt10">原因：{{ importParams.rejectReason }}</p>
      </div>
    </PageDialog>
    <!-- 添加账户 -->
    <PageDialog :title="addParams.id ? '编辑信息' : '添加信息'" :dialog-visible="addDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmAdd">
      <el-form ref="ruleForm" :model="addParams" :rules="rules" label-width="5.5rem" class="pub_form_item">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="addParams.companyName" placeholder="请输入公司名称" class="pub_input" :maxlength="50" />
        </el-form-item>
        <el-form-item label="公司编码" prop="companyCode">
          <el-input v-model="addParams.companyCode" placeholder="区分不同公司库存，建议用首字母缩写" class="pub_input" :maxlength="4" />
        </el-form-item>
        <el-form-item label="税号" prop="taxNo">
          <el-input v-model="addParams.taxNo" placeholder="请输入税号" class="pub_input" :maxlength="20" />
        </el-form-item>
        <el-form-item label="开户行A" prop="bank1">
          <el-input v-model="addParams.bank1" placeholder="请输入开户行A" class="pub_input" :maxlength="40" />
        </el-form-item>
        <el-form-item label="银行卡号A" prop="address1">
          <el-input v-model="addParams.address1" placeholder="请输入银行卡号A" class="pub_input" :maxlength="19" />
        </el-form-item>
        <el-form-item label="开户行B" prop="bank2">
          <el-input v-model="addParams.bank2" placeholder="请输入开户行B" class="pub_input" :maxlength="40" />
        </el-form-item>
        <el-form-item label="银行卡号B" prop="address2">
          <el-input v-model="addParams.address2" placeholder="请输入银行卡号B" class="pub_input" :maxlength="19" />
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 导入弹窗 -->
    <PageDialog title="上传营业执照" :dialog-visible="importDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmUpload">
      <div class="bWH ">
        <div class="cGY4 fs16 bold">注意事项</div>
        <div class="cGY3 fs14 mt8">1.公司名称将用于后续的公司认证环节，请确保准确性</div>
        <div class="cGY3 fs14 mt8">2.拍摄与所填<span class="cGR">公司全称一致</span>的营业执照并上传</div>
        <div class="cGY3 fs14 mt8">3.最新下发的营业执照</div>
        <div class="cGY3 fs14 mt8">4.营业执照信息与公章<span class="cGR">清晰可辨</span></div>
        <div class="cGY3 fs14 mt8">5.如上传<span class="cGR">复印件/彩印件</span>，请加盖<span class="cGR">公司公章</span></div>
      </div>
      <el-upload ref="upload" class="pub_upload mt16" accept="image/*" drag :data="{ file: fileList }" :show-file-list="false" :action="uploadFileUrl" :on-success="uploadFileSucess" :auto-upload="false" :limit="1" :headers="headers" :file-list="fileList" :on-remove="handleRemoveFile" :on-change="changeUploadFile">
        <img src="@/assets/img/orderManagement/import.png" alt="导入" class="pub_imgSize30 mt20 mb10" />
        <div v-show="isSelectedFile === false">
          <div class="pub_importFile_tip">将文件拖到此处，或<em class="ml5">点击上传</em></div>
          <div class="pub_importFile_tip mt10">仅支持图片</div>
        </div>
        <div v-show="isSelectedFile === true">
          <div class="pub_importFile_tip mb10">
            已导入
            <span class="pub_importFile_name">{{ fileName }}</span>
            （{{ fileSizeMB }}KB）
          </div>
          <el-button type="text" class="w108 pub_button public_cancel_btn" @click.stop="handleRemoveFile">
            <span class="ml5">重新选择</span>
          </el-button>
        </div>
      </el-upload>
    </PageDialog>
  </div>
</template>
<script>
import tableFun from '@/mixin/tableFun.js';
import { debounce } from '@/utils/debounce.js';
export default {
  mixins: [tableFun],
  data() {
    return {
      params: { commonSearch: '' },
      addParams: { companyName: '', taxNo: '', bank1: '', address1: '', bank2: '', address2: '' },
      auditList: ['待审核', '审核中', '审核通过', '驳回'],
      informationFeedbackVisilble: false, //信息反馈弹窗
      // ====== 上传文件的参数 start ======
      fileName: '', //文件名称
      importDialogVisible: false, //导入弹窗
      fileList: [], //导入的文件
      isSelectedFile: false, //是否选中文件
      fileSizeMB: 0, //上传的文件尺寸
      // ====== 上传文件的参数 end ======
      importParams: {
        id: '', //公司ID
        businessLicense: ''
      },
      // 表单验证规则
      rules: {
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          { min: 1, max: 50, message: '公司名称长度不超过50个字符', trigger: 'blur' }
        ],
        companyCode: [
          { required: true, message: '请输入公司编码', trigger: 'blur' },
          { min: 2, max: 2, message: '公司编码必须两位', trigger: 'blur' }
        ],
        taxNo: [
          { required: true, message: '请输入税号', trigger: 'blur' },
          { min: 1, max: 20, message: '税号长度不超过20个字符', trigger: 'blur' }
        ],
        bank1: [
          { required: true, message: '请输入开户行1', trigger: 'blur' },
          { min: 1, max: 40, message: '开户行1长度不超过40个字符', trigger: 'blur' }
        ],
        address1: [
          { required: true, message: '请输入银行卡号1', trigger: 'blur' },
          { min: 1, max: 19, message: '银行卡号1长度不超过19个字符', trigger: 'blur' }
        ],
        bank2: [{ min: 0, max: 40, message: '开户行2长度不超过40个字符', trigger: 'blur' }],
        address2: [{ min: 0, max: 19, message: '银行卡号2长度不超过19个字符', trigger: 'blur' }]
      }
    };
  },
  computed: {
    roleType() {
      //1:超级管理员 2:普通管理员 3:普通员工
      return this.$store.state?.userInfo?.roleType;
    },
    headers() {
      return {
        Authorization: this.$store.state.token
      };
    },
    uploadFileUrl() {
      return 'orderPlusApi/' + this.$url.uploadBusinessLicence;
    }
  },
  created() {
    this.getDataList();
  },
  methods: {
    arraySpanMethod({ rowIndex, columnIndex }) {
      // 只有在第 0, 1, 5, 6 列执行合并逻辑
      if ([0, 1, 2, 5, 6].includes(columnIndex)) {
        const currentRow = this.tableData[rowIndex];
        const prevRow = this.tableData[rowIndex - 1];
        // 如果当前行与上一行的公司名称相同，则不合并（只由上一行负责合并）
        if (prevRow && currentRow && prevRow.companyName === currentRow.companyName) {
          return { rowspan: 0, colspan: 0 };
        }
        // 当前行与下一行相同，则合并两行
        const nextRow = this.tableData[rowIndex + 1];
        if (nextRow && currentRow && currentRow.companyName === nextRow.companyName) {
          return { rowspan: 2, colspan: 1 };
        }
        // 其他情况不合并
        return { rowspan: 1, colspan: 1 };
      }
      // 其它列不合并
      return { rowspan: 1, colspan: 1 };
    },
    //关闭弹窗
    closeDialog() {
      this.selectedRow = null;
      this.multipleSelection = [];
      this.deleteDialogVisible = false;
      this.exporttDialogVisible = false;
      this.orderDialogVisible = false;
      this.importDialogVisible = false;
      this.addDialogVisible = false;
      this.informationFeedbackVisilble = false;
      this.addParams = Object.assign({}, this.$options.data().addParams); //重置参数
      this.importParams = Object.assign({}, this.$options.data().importParams); //重置参数
    },
    //获取公司列表数据
    async getDataList() {
      let { data } = await this.$api.get(this.$url.companyAll, this.params);
      let tableData = [];
      data.forEach(item => {
        let list = item.bank.split('//');
        item.addressCopy = item.address;
        item.bank1 = list[0];
        item.address1 = list.length > 1 ? list[1] : '';
        tableData.push({
          ...item,
          bank: list[0],
          address: list.length > 1 ? list[1] : ''
        });
        let arr = item.address.split('//');
        if (arr.length > 1 && arr[0] !== 'undefined' && arr[0] !== '') {
          tableData.push({
            ...item,
            bank: arr[0] === 'undefined' ? '' : arr[0],
            address: arr.length > 1 ? (arr[1] === 'undefined' ? '' : arr[1]) : ''
          });
        }
      });
      this.tableData = tableData;
    },
    //点击重新上传
    reloadUploadBtn: debounce(function() {
      this.showDilogBtn('importDialogVisible');
    }, 500),
    // ====== 上传文件的方法 start ======
    //上传文件成功
    async uploadFileSucess(file) {
      this.importParams.businessLicense = file.data.url;
      let res = await this.$api.post(this.$url.companySubmit, this.importParams);
      if (res.code == 200) {
        this.$message.success('上传成功，请等待审核');
        this.closeDialog();
        this.getDataList();
      }
    },
    //删除文件时出发此方法
    handleRemoveFile() {
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      this.fileLis = [];
      this.isSelectedFile = false;
    },
    //文件状态改变触发此方法
    changeUploadFile(file, fileList) {
      this.fileList = fileList;
      const fileSize = file.size; // 单位：字节 (Bytes)
      const fileSizeKB = Math.round(fileSize / 1024); // 转 KB
      const fileSizeMB = (fileSizeKB / 1024).toFixed(2); // 转 MB
      this.fileSizeMB = fileSizeMB;
      this.fileName = file.name;
      this.isSelectedFile = true;
    },
    //确认上传文件
    confirmUpload: debounce(function() {
      if (this.fileList.length == 0) {
        this.$message.warning('请上传文件');
      } else {
        this.$refs.upload.submit(); //上传文件
      }
    }, 500),
    // ====== 上传文件的方法 end
    //确认删除
    async confirmDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.companyDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.companyDelete, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getDataList();
      }
    },
    //确认添加
    confirmAdd: debounce(async function() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let { id } = this.addParams;
          let params = { ...this.addParams, bank: `${this.addParams.bank1}//${this.addParams.address1}`, address: `${this.addParams.bank2}//${this.addParams.address2}` };
          let url = id ? this.$url.companyUpdate : this.$url.companyAdd;
          let res = await this.$api.post(url, params);
          if (res.code === 200) {
            this.closeDialog();
            this.getDataList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    }, 500),
    //完善公司信息
    completeCompany(row) {
      this.handleRemoveFile();
      this.importParams = { ...row };
      this.importDialogVisible = true;
    },
    //查看驳回原因
    lookReruseBtn(row) {
      this.importParams = { ...row };
      this.informationFeedbackVisilble = true;
    },
    //跳转到员工信息页面
    goPage(pageUrl, item) {
      this.$router.push({ path: '/' + pageUrl, query: { companyId: item.id, activeIndex: '4-7' } });
    },
    editBtnClick(item) {
      this.addParams = Object.assign({}, item);
      if (item.addressCopy != '//') {
        let arr = item.addressCopy.split('//');
        console.log(arr);
        this.addParams.bank2 = arr[0] == 'undefined' ? '' : arr[0];
        this.addParams.address2 = arr[1] == 'undefined' ? '' : arr[1];
      }
      this.showDilogBtn('addDialogVisible');
    }
  }
};
</script>
<style lang="less" scoped>
.table_content {
  height: calc(100% - 49px);
}
.cRD2 {
  color: #ff5967;
}
</style>
